package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 智能设备Service业务层处理
 * 
 * @author zxy
 * @date 2025-05-30
 */
@Service
@Slf4j
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient client;

    @Autowired
    private RedisTemplate redisTemplate;

    public static final String ALL_PRODUCT_KEY = "iot:all_product";

    /**
     * 查询智能设备
     * 
     * @param id 智能设备主键
     * @return 智能设备
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询智能设备列表
     * 
     * @param device 智能设备
     * @return 智能设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增智能设备
     * 
     * @param device 智能设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改智能设备
     * 
     * @param device 智能设备
     * @return 结果
     */
    @Override
    public int updateDevice(DeviceDto device) {
        return 0;
    }
    /**
     * 批量删除智能设备
     * 
     * @param ids 需要删除的智能设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除智能设备信息
     * 
     * @param id 智能设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }


    /**
     * 同步华为云产品列表
     */
    @Override
    public void syncProductList() {
        log.info("同步华为云产品列表开始");
        ListProductsRequest request = new ListProductsRequest();
        ListProductsResponse response = client.listProducts(request);
        //提取需要的ID和NAME
        List<ProductSummary> products = response.getProducts();
        List<ProductVo> collect = products.stream().map(p -> new ProductVo(p.getProductId(),  p.getName()))
                .collect(Collectors.toList());
        log.info("同步华为云产品列表结束，产品列表：{}", collect);
        redisTemplate.opsForValue().set(ALL_PRODUCT_KEY, collect);
        log.info("设置redis成功");
    }

    /**
     * 获取华为云产品列表
     * @return
     */
    @Override
    public List<ProductVo> getProductList() {
        List<ProductVo> result = (List<ProductVo>)redisTemplate.opsForValue().get(ALL_PRODUCT_KEY);

        return result ;
    }

    @Override
    public void registerDevices(DeviceDto dto) {
        // 记录注册设备的开始日志
        log.info("开始注册设备：{}", dto);
        
        // 检查设备ID是否已存在
        Long count = lambdaQuery().eq(Device::getNodeId, dto.getNodeId()).count();
        if (count > 0){
            // 如果设备ID已存在，记录日志并抛出异常
            log.info("设备ID已存在");
            throw new ServiceException( "设备ID已存在");
        }
        
        // 检查设备名称是否已存在
        Long count1 = lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName()).count();
         if ( count1 > 0){
            // 如果设备名称已存在，记录日志并抛出异常
            log.info("设备名称已存在");
            throw new ServiceException( "设备名称已存在");
        }
        
        // 检查设备是否已存在（基于绑定位置、位置类型、物理位置类型和产品密钥）
        Long count2 = lambdaQuery().eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(Device::getPhysicalLocationType, dto.getPhysicalLocationType())
                .eq(Device::getProductKey, dto.getProductKey()).count();
         if ( count2 > 0){
              // 如果设备已存在，记录日志并抛出异常
              log.info("设备已存在");
              throw new ServiceException( "设备已存在");
         }

        // 创建添加设备请求对象
        AddDeviceRequest request = new AddDeviceRequest();
        
        // 创建设备信息对象
        AddDevice body = new AddDevice();
        
        // 创建认证信息对象
        AuthInfo authInfo = new AuthInfo();
        
        // 生成设备的随机密钥
        String secret = UUID.fastUUID().toString(true);
        
        // 设置设备密钥到认证信息中
        authInfo.setSecret(secret);

        // 设置设备名称
        body.setDeviceName(dto.getDeviceName());
        
        // 设置设备ID
        body.setNodeId(dto.getNodeId());
        
        // 设置产品ID
        body.setProductId(dto.getProductKey());
        
        // 设置认证信息
        body.setAuthInfo(authInfo);
        
        // 将设备信息设置到请求体中
        request.setBody(body);
        
        try {
            // 调用华为云API注册设备并获取响应
            AddDeviceResponse response = client.addDevice(request);
            
            // 将DTO转换为实体对象并设置IoT ID和密钥
            Device bean = BeanUtil.toBean(dto, Device.class);
            bean.setIotId(response.getDeviceId());
            bean.setSecret(secret);
            
            // 将设备信息保存到数据库
            save(bean);
        } catch (Exception e) {
             // 记录设备注册失败的日志并抛出异常
             log.error("设备注册华为云失败",e);
             throw new ServiceException("设备注册华为云失败");
        }
    }

    /**
     * 查询设备详情
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceByIotId(String iotId) {
        //1、通过iotId查询设备信息
        Device device = lambdaQuery().eq(Device::getIotId, iotId).one();
        if(device == null){
            throw new ServiceException("设备不存在");
        }
        DeviceDetailVo vo = BeanUtil.toBean(device, DeviceDetailVo.class);

        ShowDeviceRequest showDeviceRequest = new ShowDeviceRequest();
        showDeviceRequest.setDeviceId(iotId);
        try {
            ShowDeviceResponse response = client.showDevice(showDeviceRequest);
            vo.setDeviceStatus( response.getStatus());
            String activeTimeStr = response.getActiveTime();
            if(StringUtils.isNotEmpty(activeTimeStr)){
                LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);

                //日期时区转换, 当前所在的时区
                activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                        // 转时区,获取系统中的时区
                        .withZoneSameInstant(ZoneId.systemDefault())
                        .toLocalDateTime();
                vo.setActiveTime(activeTime);

             }
        } catch (Exception e) {
            log.error("查询云平台上的设备数据失败", e);
            throw new ServiceException("查询云平台上的设备数据失败");
        }



        return vo;
    }

    @Override
    public AjaxResult queryServiceProperties(String iotId) {
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口 - 查询设备上报数据，调用失败");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        if(CollUtil.isEmpty(shadow)){
            List<Object> emptyList = Collections.emptyList();
            return AjaxResult.success(emptyList);
        }
        //返回数据
        JSONObject jsonObject = JSONUtil.parseObj(shadow.get(0).getReported().getProperties());

        List<Map<String,Object>> list = new ArrayList<>();

        //处理上报时间日期
        LocalDateTime activeTime =  LocalDateTimeUtil.parse(shadow.get(0).getReported().getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
        //日期时区转换
        LocalDateTime eventTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();

        jsonObject.forEach((k,v)->{
            Map<String,Object> map = new HashMap<>();
            map.put("functionId",k);
            map.put("value",v);
            map.put("eventTime",eventTime);
            list.add(map);
        });

        return AjaxResult.success(list);
    }
}
